package cn.xej.easyexcel.service.impl;


import cn.xej.easyexcel.common.RespObj;
import cn.xej.easyexcel.mapper.BookMapper;
import cn.xej.easyexcel.pojo.Book;
import cn.xej.easyexcel.pojo.ClassInfo;
import cn.xej.easyexcel.service.BookService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;


    @Override
    public RespObj addBook(Book book) {
        book.setPubDate(new Date());
        bookMapper.addBook(book);
        return RespObj.build(200,"success",null);
    }

    @Override
    public RespObj getBook(long bookId) {
        Book book = bookMapper.getBookByBookId(bookId);
        return RespObj.build(200,"success",book);
    }



    @Override
    public RespObj deleteBook(long bookId) {
        bookMapper.deleteBookByBookId(bookId);
        return RespObj.build(200,"success",null);
    }

    @Override
    public JSONObject initBookTable(Integer page, Integer limit, String searchId, String searchName) {
        JSONObject jsonObject = new JSONObject();

        Map<String,Object> map = new HashMap<>();
        map.put("page",(page-1)*limit);
        map.put("limit",limit);
        if(searchId != null && searchId != ""){
            map.put("searchId","%" + searchId + "%");
        }
        if(searchName != null){
            map.put("searchName","%" + searchName+ "%");
        }


        List<Book> bookList = bookMapper.initBookTable(map);
        int count = bookMapper.initBookTableCount(map);
        jsonObject.put("msg","");
        jsonObject.put("code", 0);
        jsonObject.put("data", bookList);
        jsonObject.put("count", count);
        return jsonObject;
    }


    @Override
    public RespObj updateBook(Book book) {
        bookMapper.updateBookByBookId(book);
        return RespObj.build(200,"success",null);
    }


    @Override
    public RespObj getClassNames() {
        List<ClassInfo> classInfoList = bookMapper.getClassNames();
        return RespObj.build(200,"success",classInfoList);
    }
}
